/*
*  Copyright (c) 2001 Sun Microsystems, Inc.  All rights
*  reserved.
*
*  Redistribution and use in source and binary forms, with or without
*  modification, are permitted provided that the following conditions
*  are met:
*
*  1. Redistributions of source code must retain the above copyright
*  notice, this list of conditions and the following disclaimer.
*
*  2. Redistributions in binary form must reproduce the above copyright
*  notice, this list of conditions and the following disclaimer in
*  the documentation and/or other materials provided with the
*  distribution.
*
*  3. The end-user documentation included with the redistribution,
*  if any, must include the following acknowledgment:
*  "This product includes software developed by the
*  Sun Microsystems, Inc. for Project JXTA."
*  Alternately, this acknowledgment may appear in the software itself,
*  if and wherever such third-party acknowledgments normally appear.
*
*  4. The groups "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA"
*  must not be used to endorse or promote products derived from this
*  software without prior written permission. For written
*  permission, please contact Project JXTA at http://www.jxta.org.
*
*  5. Products derived from this software may not be called "JXTA",
*  nor may "JXTA" appear in their group, without prior written
*  permission of Sun.
*
*  THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
*  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
*  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
*  DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
*  ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
*  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
*  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
*  USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
*  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
*  OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
*  OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
*  SUCH DAMAGE.
*  ====================================================================
*
*  This software consists of voluntary contributions made by many
*  individuals on behalf of Project JXTA.  For more
*  information on Project JXTA, please see
*  <http://www.jxta.org/>.
*
*  This license is based on the BSD license adopted by the Apache Foundation.
*
*  $Id: status.java,v 1.7 2007/03/22 17:55:02 bondolo Exp $
*/

package net.jxta.myjxta.directive.directives;

import net.jxta.discovery.DiscoveryService;
import net.jxta.id.ID;
import net.jxta.impl.rendezvous.RendezVousServiceInterface;
import net.jxta.impl.rendezvous.RendezVousServiceProvider;
import net.jxta.impl.rendezvous.StdRendezVousService;
import net.jxta.impl.rendezvous.rpv.PeerView;
import net.jxta.impl.rendezvous.rpv.PeerViewElement;
import net.jxta.myjxta.directive.AbstractDirective;
import net.jxta.myjxta.directive.DirectiveException;
import net.jxta.myjxta.util.Env;
import net.jxta.myjxta.util.Group;
import net.jxta.myjxta.util.Logging;
import net.jxta.peer.PeerID;
import net.jxta.peergroup.PeerGroup;
import net.jxta.peergroup.PeerGroupID;
import net.jxta.protocol.PeerAdvertisement;
import net.jxta.protocol.PeerGroupAdvertisement;
import net.jxta.rendezvous.RendezVousService;

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

/**
 *
 * @version $Id: status.java,v 1.7 2007/03/22 17:55:02 bondolo Exp $
 *
 * @author james todd [gonzo at jxta dot org]
 */

public final class status
    extends AbstractDirective {

    private static final String TAB = "\t";
    private static final String UP = "(UP)";
    private static final String DOWN = "(DOWN)";
    private static final String NONE = "[None]";
    private static final String UNKNOWN = "[unknown]";
    
    private final Map<ID, String> names = new HashMap<ID, String>();

    private static final Logger LOG = Logger.getLogger(status.class.getName());

    public void process()
    throws DirectiveException {
        LOG.log(Logging.STATUS_LEVEL,"JXTA_HOME: " + Env.getHome());
        
        Group g = getGroup();
        PeerGroup pg = g != null ? g.getPeerGroup() : null;
        RendezVousService rdv = pg != null ? pg.getRendezVousService() : null;
        DiscoveryService dsc = pg != null ? pg.getDiscoveryService() : null;
        
        if (rdv != null) {
            LOG.log(Logging.STATUS_LEVEL," ");
            LOG.log(Logging.STATUS_LEVEL,"Rendezvous Status: ");
            LOG.log(Logging.STATUS_LEVEL,"__________________");
            LOG.log(Logging.STATUS_LEVEL," ");

            LOG.log(Logging.STATUS_LEVEL,"Current configuration : " +
                rdv.getRendezVousStatus());
            LOG.log(Logging.STATUS_LEVEL," ");
            
            StdRendezVousService srs = null;
        
            if (rdv instanceof RendezVousServiceInterface) {
                RendezVousServiceInterface rsi = (RendezVousServiceInterface)rdv;
        
                if (rsi != null) {
                    RendezVousServiceProvider rsp = rsi.getRendezvousProvider();
            
                    if (rsp instanceof StdRendezVousService) {
                        srs = (StdRendezVousService)rsp;
                    }
                }

                PeerView rpv = rsi.getPeerView();
                PeerViewElement[] pv = (PeerViewElement[])rpv.getView().
                    toArray(new PeerViewElement[0]);
            
                LOG.log(Logging.STATUS_LEVEL,"Peer View");
                
                if (pv.length > 0) {
                    for (int pvi = pv.length - 1; pvi >= 0; pvi--) {
                        System.out.print(TAB + pv[pvi] + TAB);

                        if (pv[pvi] == rpv.getUpPeer()) {
                            LOG.log(Logging.STATUS_LEVEL,TAB + UP);
                        } else if (pv[pvi] == rpv.getDownPeer()) {
                            LOG.log(Logging.STATUS_LEVEL,TAB + DOWN);
                        } else {
                            LOG.log(Logging.STATUS_LEVEL,"");
                        }
                    }
                } else {
                    LOG.log(Logging.STATUS_LEVEL,TAB + NONE);
                }
            }
            
            LOG.log(Logging.STATUS_LEVEL,"");
                        
            if (rdv.isRendezVous()) {
                Enumeration clients = rdv.getConnectedPeers();
            
                LOG.log(Logging.STATUS_LEVEL,"Rendezvous Client Connections :");
                
                if (! clients.hasMoreElements()) {
                    LOG.log(Logging.STATUS_LEVEL,TAB + NONE);
                } else {
                    while (clients.hasMoreElements()) {
//                        try {
                            ID id = (PeerID)clients.nextElement();

                            if (srs != null) {
                                LOG.log(Logging.STATUS_LEVEL,TAB + srs.getPeerConnection(id));
                            } else {
                                LOG.log(Logging.STATUS_LEVEL,TAB + idToName(dsc, id));
                            }
//                        } catch (Exception e) {
//                        }
                    }
                }
                
                LOG.log(Logging.STATUS_LEVEL,"");
            } else {
                Enumeration rdvs = rdv.getConnectedRendezVous();
            
                LOG.log(Logging.STATUS_LEVEL,"Rendezvous Connections :");
                
                if (rdvs.hasMoreElements()) {
                    while (rdvs.hasMoreElements()) {
//                        try {
                            ID id = (PeerID)rdvs.nextElement();
                            
                            if (srs != null) {
                                LOG.log(Logging.STATUS_LEVEL,TAB +
                                    srs.getPeerConnection(id));
                            } else {
                                LOG.log(Logging.STATUS_LEVEL,TAB + idToName(dsc, id));
                            }
//                        } catch (Exception e) {
//                        }
                    }
                } else {
                    LOG.log(Logging.STATUS_LEVEL,TAB + NONE);
                }
                
                LOG.log(Logging.STATUS_LEVEL,"");
            
                Enumeration rmRdvs = rdv.getDisconnectedRendezVous();
            
                LOG.log(Logging.STATUS_LEVEL,"Rendezvous Disconnections :");
                
                if (rmRdvs.hasMoreElements()) {
                    while (rmRdvs.hasMoreElements()) {
//                        try {
                            ID id = (PeerID)rmRdvs.nextElement();
                        
                            System.out.print(TAB);
                            LOG.log(Logging.STATUS_LEVEL,TAB + idToName(dsc, id));
//                        } catch (Exception e) {
//                        }
                    }
                } else {
                    LOG.log(Logging.STATUS_LEVEL,TAB + NONE);
                }
                
                LOG.log(Logging.STATUS_LEVEL,"");
            }
        } else {
            LOG.log(Logging.STATUS_LEVEL,"No Rendezvous Service");
        }
    }
    
    private String idToName(DiscoveryService dsc, ID id) {
        String idstring = id.toString();
        String name = names.get(id);
        
        if(name == null) {
            try {
                Enumeration res;
            
                if (id instanceof PeerID) {
                    res = dsc.getLocalAdvertisements(DiscoveryService.PEER,
                        "PID", idstring);
                
                    if (res.hasMoreElements()) {
                        name = ((PeerAdvertisement)res.nextElement()).getName();
                    }
                } else if (id instanceof PeerGroupID) {
                    res = dsc.getLocalAdvertisements(DiscoveryService.GROUP,
                        "GID", idstring);
                
                    if (res.hasMoreElements()) {
                        name = ((PeerGroupAdvertisement)res.nextElement()).getName();
                    }
                }
            } catch( IOException failed ) {
            }
        
            if (name != null) {
                names.put(id, name);
            } else {
                name = UNKNOWN;
            }
        }
        
        return name;
    }
}
